kotlin+mvvm+databinding+recyclerview
上一篇講了一般kotlin的recyclereview的寫法,這次來整合databinging跟MVVM。
首先是xml(主畫面)
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="@layout/item_view"
tools:itemCount="5" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
再來是item_view的xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="Post"
type="com.example.myapplication.Post" />
<variable
name="listener"
type="com.example.myapplication.Listener" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:padding="5dp"
android:textSize="16sp"
android:text="@{Post.post}"
android:onClick="@{()-> listener.onClick(Post)}"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
今天主要先說Activity的部分
class Activity:AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private val mViewModel by lazy {
initViewModel(application, ViewModel::class.java)
}
private val mAdapter by lazy {
Adapter<Post>(
R.layout.item_view,
listener = object : Listener<Post> {
override fun onClick(post: Post) {
Toast.makeText(this@Activity, post.post, Toast.LENGTH_SHORT).show()
}
}
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.recyclerView.adapter = mAdapter
mViewModel.data.observe(this, Observer { post ->
mAdapter.updateData(post)
})
mViewModel.fetchData()
}
}
這邊的lazy是讓程式執行時,需要的時後在讀取,可以提升程式執行速度及記憶體空間的利用
listener是我自定義onclick的interface
因為後面的viewmodel是繼承androidviewmodel,所以我用一個擴展含式,去取的程式的application的上下文,也可以直接在manifests裡面新增